param([string]$serviceName = "");

### BEGIN SELF-ELEVATION ###

# Get the ID and security principal of the current user account

$myWindowsID=[System.Security.Principal.WindowsIdentity]::GetCurrent();
$myWindowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($myWindowsID);

# Get the security principal for the Administrator role
$adminRole=[System.Security.Principal.WindowsBuiltInRole]::Administrator;

# Check to see if we are currently running "as Administrator"
if (-Not $myWindowsPrincipal.IsInRole($adminRole))
{
	$arguments = "& '" + $myinvocation.mycommand.definition + "'"
	Start-Process powershell -Verb runAs -ArgumentList $arguments
	exit;
}

### END SELF-ELEVATION ###

# Define Names
$plist_path = $PSScriptRoot + "\..\Info.plist"
Write-Host $plist_path

[xml]$InfoPlist = Get-Content -Path $plist_path;
$appName = $InfoPlist.SelectSingleNode("//key[text()='CFBundleDisplayName']").get_nextsibling()."#text";
Write-Host "appName is " $appName;


if($serviceName -eq "")
{
	$serviceName = "VSS " + $appName;
}

# Define Folders
$VSSAppdataFolder  = $env:ALLUSERSPROFILE + "\" + $appName + "\VSS\";
$VSSResourceFolder = $PSScriptRoot + "\";

$ResourceBinaryPath = $VSSResourceFolder + "vss_writer.exe";
$AppDataBinaryPath = $VSSAppdataFolder + "VSS " + $appName + ".exe";

# Does the service Exist at all ?
if ($serviceObj = Get-Service $serviceName -ErrorAction SilentlyContinue)
{
	# Is it Running ?
	if( ($serviceObj | select -expand "status") -eq "running" )
	{
		Write-Host "Stopping Service " $serviceName;
		Stop-Service $serviceName;
		Get-Service -Name $serviceName | % { $_.WaitForStatus([System.ServiceProcess.ServiceControllerStatus]::Stopped, "00:01:00") };
	}

	Write-Host "Deleting Service " $serviceName;
    sc.exe delete $serviceName;

	start-sleep -seconds 1;
	Write-Host "waiting for service to be deleted. Please close any SC manager if open";

	$timeout = new-timespan -Minutes 1;
	$sw = [diagnostics.stopwatch]::StartNew();
	while ( ($sw.elapsed -lt $timeout) -And (Get-Service $serviceName -ErrorAction SilentlyContinue) )
	{
		start-sleep -seconds 1;
	}

	if (Get-Service $serviceName -ErrorAction SilentlyContinue)
	{
			Write-Host "Failed to delete Service";
			exit;
	}
}

# delete the %appdata% directory
Write-Host "removing " $VSSAppdataFolder;
Remove-Item -Recurse -Force $VSSAppdataFolder;

# this line is useless in many cases, but If this script as non admin is launched from a xxx.cmd using:
# > powershell -executionPolicy bypass -file "%~dp0\InstallService.ps1"
# This lines fire and event VSSIsUnInstalled which the script can wait for using "waitfor /t 60 VSSIsUnInstalled " for instance...
waitfor /si VSSIsUnInstalled

# DEBUG LINES... If you want not to exit after completion
# Read-Host -Prompt "Press Enter to continue"
# Note $host.UI.RawUI.ReadKey will not work inside powershell ISE...
exit;
